package com.oss.client;


import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import lombok.RequiredArgsConstructor;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * s3 是一个协议
 * S3是Simple Storage Service的缩写，即简单存储服务
 * @author zdh
 */
@RequiredArgsConstructor
public class S3OssClient implements OssClient {

    private final AmazonS3 amazonS3;
    private final String defaultBucket;


    @Override
    public void createBucket(String bucketName) {
        if (!amazonS3.doesBucketExistV2(bucketName)) {
            amazonS3.createBucket((bucketName));
        }
    }

    @Override
    public String getObjectURL(String bucketName, String objectName) {
        URL url = amazonS3.getUrl(bucketName, objectName);
        return url.toString();
    }

    /**
     * 使用默认的bucket
     *
     * @param objectName
     * @return
     */
    @Override
    public String getObjectURL(String objectName) {
        checkDefaultBucketName();
        return getObjectURL(defaultBucket,objectName);
    }

    @Override
    public S3Object getObjectInfo(String bucketName, String objectName) {
        return amazonS3.getObject(bucketName, objectName);
    }

    /**
     * <p>
     * 使用默认的bucket
     * </p>
     *
     * @param objectName
     * @return
     */
    @Override
    public S3Object getObjectInfo(String objectName) {
        checkDefaultBucketName();
        return getObjectInfo(defaultBucket,objectName);
    }

    @Override
    public PutObjectResult putObject(String bucketName, String objectName, InputStream stream, long size, String contextType) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(size);
        objectMetadata.setContentType(contextType);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, stream, objectMetadata);
        putObjectRequest.getRequestClientOptions().setReadLimit(Long.valueOf(size).intValue() + 1);
        return amazonS3.putObject(putObjectRequest);
    }


    @Override
    public PutObjectResult putObject(String objectName, InputStream stream, int available, String s) throws IOException {
        checkDefaultBucketName();
        return putObject(defaultBucket,objectName,stream,available,s);
    }

    @Override
    public ObjectListing listObjects(String bucketName, String key) {
        return amazonS3.listObjects(bucketName,key);
    }

    @Override
    public ObjectListing listObjects(String key) {
        return listObjects(defaultBucket,key);
    }

    @Override
    public AmazonS3 getS3Client() {
        return amazonS3;
    }

    /**
     * 检查默认的bucket是否设置,如果没有设置则抛出异常
     */
    private void checkDefaultBucketName(){
         if(defaultBucket==null || defaultBucket.trim().isEmpty()){
             throw new IllegalArgumentException("默认bucketName未进行设置,或者设置为空");
         }
    }
}
